package sso.client2.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import sso.client2.utils.LocalSessionsUtil;
import sso.client2.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class IndexController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String ssoServer = "http://localhost:8080";

    @RequestMapping("/index")
    public String index(){
        return "/index";
    }

    @RequestMapping("/logout")
    @SuppressWarnings("all")
    public void logout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        // 本地会话id，SSO回调退出时需要的参数
        String localSessionId = request.getParameter("localSessionId");
        if (StringUtil.isEmpty(localSessionId)) {// 用户点击退出
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath()+"/";
            // 重定向到SSO的退出接口
            try {
                response.sendRedirect(ssoServer + "/auth/logout?server=" + basePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //return "redirect:" + ssoServer + "/auth/logout?server=" + basePath;
        } else {// SSO回调退出
            logger.info("认证中心回调退出");
            // 销毁本地session
            HttpSession localSession = LocalSessionsUtil.get(localSessionId);
            if (localSession != null) {
                localSession.invalidate();// 销毁
                LocalSessionsUtil.remove(localSessionId);
            } else {
                logger.info("已经退出，无需重复退出！");
            }
        }
    }

}
